<template>
  <div class='articlelist'>
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="pullRefreshIsLoading" @refresh="onRefresh" :success-text="tiptext">
      <!-- list列表 -->
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" :error.sync="error"
        error-text="请求失败，点击重新加载" @load="onLoad">
        <!-- 文章项的组件 -->
        <Articleitem :article='item' v-for="item in list" :key="item.art_id+''"></Articleitem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 引入文章列表请求
import { getArticleList } from '@/api/article'
// 文章项的组件
import Articleitem from '@/components/article-item.vue'
export default {
  data () {
    return {
      // 文章列表数据
      list: [],
      // 加载显示
      loading: false,
      // 完成显示
      finished: false,
      // 时间戳
      pre_timestamp: Date.now(),
      // 错误信息
      error: false,
      // 下拉加载显示
      pullRefreshIsLoading: false,
      // 下拉的提示文本
      tiptext: ''
    }
  },
  props: {
    // 文章列表参数
    channelId: {
      type: Number,
      required: true
    }
  },
  methods: {
    // 进行文章列表数据获取
    async onLoad () {
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: this.pre_timestamp,
          with_top: 0
        })
        // 随机出现错误
        // if (Math.random() > 0.5) {
        //   console.lg(123)
        // }
        this.list.push(...res.data.data.results)
        this.pre_timestamp = res.data.data.pre_timestamp
        // 加载状态结束
        this.loading = false
        if (!res.data.data.results.length) {
          this.finished = true
        }
      } catch (err) {
        // 错误信息显示
        this.error = true
        this.loading = false
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 0
        })
        // 随机出现错误
        if (Math.random() > 0.5) {
          console.lg(123)
        }
        this.list.unshift(...res.data.data.results)
        this.pullRefreshIsLoading = false
        this.tiptext = '一共加载' + res.data.data.results.length + '条数据'
      } catch (err) {
        this.pullRefreshIsLoading = false
        this.tiptext = '加载失败'
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {
    // 文章项组件
    Articleitem
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.articlelist {
  height: 80vh;
  overflow-y: scroll;
}
</style>
